package com.digua.base.util

import android.os.AsyncTask
import android.os.SystemClock

object ThreadUtil {
    fun post(lambda: () -> Unit): Thread {
        val thread = Thread { lambda() }
        thread.start()
        return thread
    }

    fun postDelayed(sleep: Long, lambda: () -> Unit): Thread {
        val thread = Thread {
            if (sleep > 0) SystemClock.sleep(sleep)
            lambda()
        }
        thread.start()
        return thread
    }

    fun async(lambda: () -> Unit) = async(1, lambda)

    fun async(sleep: Long = 1L, lambda: () -> Unit): AsyncTask<Long, Unit, Unit> {
        val task = object : AsyncTask<Long, Unit, Unit>() {

            override fun doInBackground(vararg sleep: Long?) {
                sleep[0]?.let { SystemClock.sleep(it) }
            }

            override fun onPostExecute(result: Unit?) {
                lambda()
            }
        }
        task.execute(sleep)
        return task
    }
}